package com.ruantu.clothing.controller;

import com.ruantu.clothing.entity.*;
import com.ruantu.clothing.service.ProductionService;
import com.ruantu.clothing.util.MyException;
import javafx.scene.control.ComboBox;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/5/28 0028.
 */
@Controller
@RequestMapping("/production")
public class ProductionController {

    private static final Logger logger = LoggerFactory.getLogger(ProductionController.class);

    @Autowired
    private ProductionService productionService;

    @ResponseBody
    @RequestMapping("/findall")
    public JsonResponseMessage findAll(Production production, PageBean pageBean, HttpSession session) {
        User user = (User) session.getAttribute("info");
        production.setJgId(user.getJgid());
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        jsonResponseMessage.setRows(productionService.findAll(production, pageBean));
        jsonResponseMessage.setTotal(pageBean.getTotal());
        return jsonResponseMessage;
    }


    @RequestMapping("/downloadExcelMuban")
    @ResponseBody
    public void daoChuMobanOrderUser(ServletOutputStream out, HttpServletResponse response) {
        try {
            XSSFWorkbook wb = productionService.download();
            HttpHeaders headers = new HttpHeaders();
            ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
            String fileName = URLEncoder.encode("商品导入模板.xls", "utf-8");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            wb.write(out);
            outByteStream.flush();
            outByteStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 导入excel
     *
     * @param files
     * @param session
     * @return
     */
    @RequestMapping("/daoruexcel")
    @ResponseBody
    public JsonResponseMessage daoruExcel(@RequestParam(value = "excel", required = false) MultipartFile files,
                                          @RequestParam(value = "gongyingshang", required = false) String gongyingshang,
                                          HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            //读取excel数据
            List<Production> list = productionService.daoRuExcel(files, user, gongyingshang);
            //将导入的excel数据插入数据库中
            productionService.insertSome(list);
            jsonResponseMessage.setCode(200);
        } catch (MyException e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setCode(400);
            jsonResponseMessage.setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setCode(400);
            jsonResponseMessage.setMsg("服务器内部错误，请检查重试");
        }
        return jsonResponseMessage;
    }

    /**
     * @param production
     * @return
     */
    @RequestMapping("/update/state")
    @ResponseBody
    public JsonResponseMessage updateState(Production production, HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            production.setUpdateBy(user.getId());
            productionService.updateState(production);
            jsonResponseMessage.setCode(200);
        } catch (MyException e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg("服务器内部错误，请联系管理员重试!");
        }
        return jsonResponseMessage;
    }

    /**
     * 删除商品
     *
     * @param production
     * @return
     */
    @RequestMapping("/del")
    @ResponseBody
    public JsonResponseMessage del(Production production) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        try {
            productionService.delProduction(production);
            jsonResponseMessage.setCode(200);
        } catch (MyException e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg("服务器内部错误，请刷新重试!");
        }
        return jsonResponseMessage;
    }

    /**
     * 查询所有combobox
     *
     * @param
     * @return
     */
    @RequestMapping("/combobox")
    @ResponseBody
    public JsonResponseMessage findcombobox(HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        try {
            jsonResponseMessage.setData(productionService.findCombobox(user.getJgid()));
            jsonResponseMessage.setCode(200);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg("服务器内部错误，请联系管理员重试!");
            jsonResponseMessage.setCode(400);
        }
        return jsonResponseMessage;
    }


    /**
     * 保存商品
     *
     * @param production
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public JsonResponseMessage save(Production production, HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        try {
            production.setJgId(user.getJgid());
            production.setCreateBy(user.getId());
            production.setUpdateBy(user.getId());
            productionService.save(production);
            jsonResponseMessage.setCode(200);
        } catch (NullPointerException e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg("服务器连接已断开，请重新登录进行尝试");
            jsonResponseMessage.setCode(400);
        } catch (MyException e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg(e.getMessage());
            jsonResponseMessage.setCode(400);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setCode(400);
            jsonResponseMessage.setMsg("服务器内部错误，请联系管理员重试!");
        }
        return jsonResponseMessage;
    }


    /**
     * 查询商品是否存在
     *
     * @param production
     * @return
     */
    @RequestMapping("/find/kuanhao")
    @ResponseBody
    public JsonResponseMessage findNone(Production production) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        int code = productionService.findByProduct(production);
        if (code > 0) {
            jsonResponseMessage.setCode(400);
        } else {
            jsonResponseMessage.setCode(200);
        }
        return jsonResponseMessage;
    }


    /**
     * 根据id反显
     *
     * @param production
     * @return
     */
    @RequestMapping("/find/id")
    @ResponseBody
    public JsonResponseMessage findByid(Production production) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        Production prod = productionService.findById(production);
        if (prod != null) {
            jsonResponseMessage.setCode(200);
            jsonResponseMessage.setData(prod);
        } else {
            jsonResponseMessage.setCode(400);
            jsonResponseMessage.setMsg("修改失败，该款号不存在");
        }
        return jsonResponseMessage;
    }


    /**
     * 查询所有可用的款号，裁剪combobox用
     *
     * @param
     * @return
     */
    @RequestMapping("/combobox/list")
    @ResponseBody
    public List<Production> findProductCombobox(HttpSession session) {
        User user = (User) session.getAttribute("info");
        Production production = new Production();
        production.setJgId(user.getJgid());
        return productionService.findProductCombobox(production);
    }

    /**
     * 查询所有次品厂可用的款号，入库次品combobox用
     *
     * @param
     * @return
     */
    @RequestMapping("/combobox/cipinstore")
    @ResponseBody
    public List<Production> findCipinForProduct() {
        return productionService.findCipinForProduct();
    }

    /**
     * 查询所有可用的款号
     *
     * @param
     * @return
     */
    @RequestMapping("/combobox/zongbu")
    @ResponseBody
    public List<Production> findProductZongbu() {
        return productionService.findProductComboboxZongbu();
    }

    /**
     * 根据裁剪id查询款号详细数据
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/diaopai/tailorid")
    public List<Production> findDiaopai(Production production, HttpSession session) {
        User user = (User) session.getAttribute("info");
        production.setJgId(user.getJgid());
        return productionService.findProductByTailorId(production);
    }

    /**
     * 获得所有已生效商品
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/allysxpro")
    public JsonResponseMessage findAllProForJGId(HttpSession session) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            List<Production> list = productionService.findAllForJGService(user);
            if (list != null) {
                msg.setMsg("数据获取成功");
                msg.setCode(200);
                msg.setData(list);
            } else {
                msg.setCode(1);
                msg.setMsg("暂无数据");
            }
        } catch (Exception e) {
            msg.setCode(400);
            e.printStackTrace();
            msg.setMsg("数据异常,请联系管理员!");
        }
        return msg;
    }


    /**
     * 获得所有已生效商品
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/findAllProForChuKuId")
    public JsonResponseMessage findAllProForChuKuId(HttpSession session, String chukuId) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            List<Production> list1 = productionService.findAllProductForChuKuId(chukuId);
            if (list1 != null) {
                msg.setMsg("数据获取成功");
                msg.setCode(200);
                msg.setData(list1);
            } else {
                msg.setCode(1);
                msg.setMsg("暂无数据");
            }
        } catch (MyException e) {
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常!");
        }
        return msg;
    }


    /**
     * 下级机构录入非本公司的产品
     *
     * @param
     * @return
     */
    @RequestMapping("/savedown")
    @ResponseBody
    public JsonResponseMessage saveDown(Production production, HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        try {
            production.setJgId(user.getJgid());
            production.setCreateBy(user.getId());
            production.setUpdateBy(user.getId());
            productionService.saveDown(production);
            jsonResponseMessage.setCode(200);
        } catch (NullPointerException e) {
            jsonResponseMessage.setMsg("服务器连接已断开，请重新登录进行尝试");
        } catch (MyException e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg(e.getMessage());
            jsonResponseMessage.setCode(400);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setCode(400);
            jsonResponseMessage.setMsg("服务器内部错误，请联系管理员重试!");
        }
        return jsonResponseMessage;
    }

    /**
     * 查询零售销售code
     *
     * @return
     */
    @RequestMapping("/findsale/list")
    @ResponseBody
    public JsonResponseMessage findSaleList(Production production, HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        try {
            production.setJgId(user.getJgid());
        } catch (NullPointerException e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setCode(400);
            jsonResponseMessage.setMsg("服务器连接已断开，请重新登录进行尝试!");
        }
        jsonResponseMessage.setData(productionService.findSaleProductCode(production));
        return jsonResponseMessage;
    }


    /**
     * 查询零售销售code
     *
     * @return
     */
    @RequestMapping("/findsale/productiondetailsid")
    @ResponseBody
    public JsonResponseMessage findSaleByProductionDetailsId(Sale sale, HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        if (user != null) {
            sale.setJgId(user.getJgid());
            jsonResponseMessage.setData(productionService.findSaleByProductionDetailsId(sale));
            jsonResponseMessage.setCode(200);
        } else {
            jsonResponseMessage.setMsg("服务器连接已断开，请重新登录尝试");
            jsonResponseMessage.setCode(400);
        }
        return jsonResponseMessage;
    }

    /**
     * 查询季节折扣策略用
     *
     * @return
     */
    @RequestMapping("/findseasonzk")
    @ResponseBody
    public List<Combobox> findSeasonWithZk() {
        return productionService.findSeasonCombobox("1");
    }


    /**
     * 获得所有已生效商品
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/findAllProForkehuid")
    public JsonResponseMessage selectChuKuProductForKeHuIdService(HttpSession session, String kehuId) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            List<Production> list = productionService.selectChuKuProductForKeHuIdService(kehuId);
            if (list != null) {
                msg.setMsg("数据获取成功");
                msg.setCode(200);
                msg.setData(list);
            } else {
                msg.setCode(1);
                msg.setMsg("暂无数据");
            }
        } catch (MyException e) {
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常!");
        }
        return msg;
    }

    /**
     * 获得所有已生效商品
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectallattr")
    public JsonResponseMessage selectAllAttrService(HttpSession session) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            Map<String, Object> list = productionService.selectAllAttrService(user);
            msg.setData(list);
            msg.setMsg("获取数据成功!");
            msg.setCode(200);
        } catch (MyException e) {
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常!");
        }
        return msg;
    }


    @RequestMapping("/downloadproduct")
    @ResponseBody
    public void daochuProduct(Production production, ServletOutputStream out, HttpServletResponse response, HttpSession session) {
        try {
            User user = (User) session.getAttribute("info");
            if (user == null) {
                throw new RuntimeException("网络连接中断，请刷新重试");
            }
            production.setJgId(user.getJgid());
            XSSFWorkbook wb = productionService.downExcel(production);
            HttpHeaders headers = new HttpHeaders();
            ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
            String fileName = URLEncoder.encode("商品信息.xls", "utf-8");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            wb.write(out);
            outByteStream.flush();
            outByteStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


}
